package com.kaluli.project.service;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.kaluli.project.domain.entity.CpsUserVO;
import com.kaluli.project.domain.entity.EntityConverter;
import com.kaluli.project.domain.entity.KllMq;
import com.kaluli.project.domain.entity.KllMqBak;
import com.kaluli.project.domain.entity.KllOptlog;
import com.kaluli.project.domain.entity.KllOptlogBak;
import com.kaluli.project.domain.entity.StockVO;
import com.kaluli.project.domain.repository.KllMqBakRepository;
import com.kaluli.project.domain.repository.KllMqRepository;
import com.kaluli.project.domain.repository.KllOptlogBakRepository;
import com.kaluli.project.domain.repository.KllOptlogRepository;
import com.kaluli.project.domain.repository.KllStockRepository;

import freemarker.template.Template;

@Service
@Configuration
@Component
@PropertySource({ "classpath:mail.properties","classpath:thridsystem.properties" })
public class KllCornApiService {

	@Autowired
	private Environment env;


	@Autowired
	private KllMqBakRepository kllMqBakRepository;
	
	@Autowired
	private KllMqRepository kllMqRepository;
	
	@Autowired
	private KllOptlogRepository kllOptlogRepository;
	
	@Autowired
	private KllOptlogBakRepository kllOptlogBakRepository;
	
	@Autowired
	private KllStockRepository kllStockRepository;
	
	@Autowired
	private StockNumService stockNumService;
	
	@Autowired
	private SendEmailService sendEmailService;
	
	@Autowired
	private KllDataService dataService;

	static Logger log = Logger.getLogger(KllCornApiService.class);
	
	
	

	/**
	 * 定期转移mq表中数据
	 * 
	 * @throws Exception
	 */
	@Scheduled(cron = "${moveMq.pool.cron}")
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void moveMqToPool() throws Exception {
		
		List<KllMq> mqlist=kllMqRepository.findMoveList();
		List<KllMqBak> departmentVOList = new EntityConverter<KllMq, KllMqBak>().convertFromModelList(mqlist,
				 KllMqBak.class);
		for (KllMqBak kllMqBak : departmentVOList) {
			kllMqBakRepository.save(kllMqBak);
		}
		
		for (KllMq kllMq : mqlist) {
			kllMqRepository.remove(kllMq);
		}
		
	}
	
	

	/**
	 * 定期转移log表中数据
	 * 
	 * @throws Exception
	 */
	@Scheduled(cron = "${moveLog.pool.cron}")
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void moveLogToPool() throws Exception {
		
		List<KllOptlog> loglist=kllOptlogRepository.findMoveList();
		List<KllOptlogBak> bakList = new EntityConverter<KllOptlog, KllOptlogBak>().convertFromModelList(loglist,
				KllOptlogBak.class);
		for (KllOptlogBak bak : bakList) {
			kllOptlogBakRepository.save(bak);
		}
		
		for (KllOptlog log : loglist) {
			kllOptlogRepository.remove(log);
		}
		
	}
	
	/**
	 * 定时发送库存预警信息
	 * 
	 * @throws Exception
	 */
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void findStockNum() throws Exception {
		
		List<StockVO> stockList = kllStockRepository.findStockNum();
		if(stockList != null && stockList.size()>0){
			
			freemarker.template.Configuration cfg = new freemarker.template.Configuration();
			HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
			cfg.setDefaultEncoding("UTF-8");
			Template t = cfg.getTemplate("list.ftl");
			StringWriter out = new StringWriter();
			Map<String, List> map = new HashMap<>();
			map.put("stockList", stockList);
			t.process(map, out);
			String title = env.getProperty("nsapi.mail.kaluli");
			sendEmailService.sendExmailHtml(out.toString(), env.getProperty("nsapi.mail.stocknum"),title);
//			stockNumService.sendEmailByStock(stockList);
		}
		
	}
	
	
	/**
	 * 定时发送用户活跃数据日报
	 * 
	 * @throws Exception
	 */
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void findUserData() throws Exception {
		
		Map map = dataService.findUserData();
			
		freemarker.template.Configuration cfg = new freemarker.template.Configuration();
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
		cfg.setDefaultEncoding("UTF-8");
		Template t = cfg.getTemplate("userOrder.ftl");
		StringWriter out = new StringWriter();
		t.process(map, out);
		String title = env.getProperty("nsapi.mail.day");
		sendEmailService.sendExmailHtml(out.toString(), env.getProperty("nsapi.mail.user"),title);
		
	}
	
	
	/**
	 * 定时发送用户活跃数据周报
	 * 
	 * @throws Exception
	 */
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void findUserDataWeek() throws Exception {
//		Map data = new HashMap<>();
		
		Map map = dataService.findUserDataByWeek("All");
		/*data.put("date",DateUtil.OneWeekStr()+"-"+DateUtil.getCurrentDay());
		data.put("oneProp",map.get("oneProp"));
		data.put("twoProp",map.get("twoProp"));
		data.put("threeProp",map.get("threeProp"));
		data.put("fourProp",map.get("fourProp"));
		data.put("weekCnt",map.get("weekCnt"));*/
		/*//m
		data.put("onePropm",m.get("oneProp"));
		data.put("twoPropm",m.get("twoProp"));
		data.put("threePropm",m.get("threeProp"));
		data.put("fourPropm",m.get("fourProp"));
		data.put("weekCntm",m.get("weekCnt"));*/
		
		
			
		freemarker.template.Configuration cfg = new freemarker.template.Configuration();
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
		cfg.setDefaultEncoding("UTF-8");
		Template t = cfg.getTemplate("week.ftl");
		StringWriter out = new StringWriter();
		t.process(map, out);
		String title = env.getProperty("nsapi.mail.week");
		sendEmailService.sendExmailHtml(out.toString(), env.getProperty("nsapi.mail.user"),title);
		
	}
	
	
	/**
	 * 定时发送新用户渠道数据	
	 * 
	 * @throws Exception
	 */
	@Transactional(rollbackOn = { RuntimeException.class, Exception.class })
	public synchronized void findCpsUser() throws Exception {
		
		List<CpsUserVO> cpsList = dataService.findByCps();
		if(cpsList == null){
			return;
		}
		freemarker.template.Configuration cfg = new freemarker.template.Configuration();
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "/template");
		cfg.setDefaultEncoding("UTF-8");
		Template t = cfg.getTemplate("cpsUser.ftl");
		StringWriter out = new StringWriter();
		Map<String, List> map = new HashMap<>();
		map.put("cpsList", cpsList);
		t.process(map, out);
		String title = env.getProperty("nsapi.mail.cps");
		sendEmailService.sendExmailHtml(out.toString(), env.getProperty("nsapi.mail.user"),title);
		
	}
	


}
